<template>
  <div class="bg-in-stock">
    <el-form ref="goodsExchangeAddForm" :model="goodsExchangeAddForm" :rules="goodsExchangeAddFormRule"
      label-width="120px" inline class="change-form">
      <h3 style="width: 100%;">换货单</h3>
      <el-form-item label="换货单编号" prop="sn" v-if="type === 'edit' || type === 'detail' || type === 'audit'"
        class="change-form-item">
        <el-input v-model="goodsExchangeAddForm.sn" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="订单编号" prop="order_sn" class="change-form-item">
        <el-button v-if="goodsExchangeAddForm && goodsExchangeAddForm.order_sn"
          :disabled="type === 'edit' || type === 'detail' || type === 'audit'" class="button" size="mini" type="text"
          @click="handleSelectOrderSn">{{ goodsExchangeAddForm.order_sn }}</el-button>
        <el-button v-else :disabled="type === 'edit' || type === 'detail' || type === 'audit'" class="button" size="mini"
          type="primary" @click="handleSelectOrderSn">选择</el-button>
      </el-form-item>
      <el-form-item label="服务专员" class="change-form-item">
        <el-input v-model="goodsExchangeAddForm.distribution_name" disabled></el-input>
      </el-form-item>
      <el-form-item label="所属部门" prop="username" class="change-form-item">
        <el-cascader v-model="goodsExchangeAddForm.dept_id" :options="deptList"
          :disabled="type === 'detail' || type === 'audit'" :props="{
            label: 'name',
            value: 'id',
            emitPath: false,
            checkStrictly: true
          }" clearable @change="changewarehouseList"></el-cascader>
      </el-form-item>
      <el-form-item label="仓库" class="change-form-item">
        <el-select v-model="goodsExchangeAddForm.warehouse_id" @change="handleChangeWareHouse"
          :disabled="type === 'detail' || type === 'audit'">
          <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="换货时间" prop="change_time" class="change-form-item">
        <el-date-picker v-model="goodsExchangeAddForm.change_time" value-format="timestamp" type="datetime"
          :disabled="type === 'detail' || type === 'audit'" placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="换货金额" prop="change_amount" class="change-form-item">
        ¥{{ goodsExchangeAddForm.change_amount }}
      </el-form-item>
      <el-form-item label="经手人" prop="handled_by_id" class="change-form-item">
        <el-select v-model="goodsExchangeAddForm.handled_by_id" :disabled="type === 'detail' || type === 'audit'">
          <el-option v-for="item in adminList" :key="item.id" :label="item.real_name" :value="item.id" />
        </el-select>
        <!-- <el-input v-model="goodsExchangeAddForm.handled_by" :minlength="2" :maxlength="20" clearable
          :disabled="type === 'detail'" placeholder="请输入经手人"></el-input> -->
      </el-form-item>
      <el-form-item label="换货说明" prop="change_desc" class="change-form-item" style="width: 61%;">
        <el-input style="flex: 1;" v-model="goodsExchangeAddForm.change_desc" type="textarea"
          :disabled="type === 'detail' || type === 'audit'" :autosize="{ minRows: 3, maxRows: 4 }"
          placeholder="请输入换货说明"></el-input>
      </el-form-item>
      <div class="mx">
        <h3>退货商品明细</h3>
      </div>
      <div style="width: 100%; display: block;">
        <el-form-item style="width: 100%;">
          <el-table :data="goodsExchangeAddForm.return_list" border :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }" style="width: 100%; margin-top: 20px;">
            <el-table-column label="入库单号">
              <template slot-scope="scope">
                {{ scope.row.stock_sn }}
              </template>
            </el-table-column>
            <el-table-column label="商品编号">
              <template slot-scope="scope">
                {{ scope.row.product_sn }}
              </template>
            </el-table-column>
            <el-table-column label="商品名称">
              <template slot-scope="scope">
                {{ scope.row.product_name }}
              </template>
            </el-table-column>
            <el-table-column label="规格型号">
              <template slot-scope="scope">
                {{ scope.row.specification }}
              </template>
            </el-table-column>
            <el-table-column label="单位">
              <template slot-scope="scope">
                {{ scope.row.unit }}
              </template>
            </el-table-column>
            <el-table-column label="单价">
              <template slot-scope="scope">
                ¥{{ scope.row.amount }}
              </template>
            </el-table-column>
            <el-table-column label="数量">
              <template slot-scope="scope">
                <el-input v-model="scope.row.num" type="number" :min="0" :maxlength="20"
                  :disabled="type === 'detail' || type === 'audit'"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="金额">
              <template slot-scope="scope">
                {{ scope.row.num * scope.row.amount || 0 }}
              </template>
            </el-table-column>
            <el-table-column label="操作" v-if="type !== 'detail' && type !== 'audit'">
              <template slot-scope="scope">
                <el-button size="mini" type="danger"
                  @click="goodsExchangeAddForm.return_list.splice(scope.$index, 1)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </div>
      <div class="mx">
        <h3>换货商品明细</h3>
        <el-button class="button" size="mini" type="primary" v-if="type !== 'detail' && type !== 'audit'"
          @click="handleSelectWarehouseEntryBatch">选择</el-button>
      </div>
      <div style="width: 100%; display: block;">
        <el-form-item style="width: 100%;">
          <el-table :data="goodsExchangeAddForm.change_list" border :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }" style="width: 100%; margin-top: 20px;">
            <el-table-column label="入库单号">
              <template slot-scope="scope">
                {{ scope.row.stock_sn }}
              </template>
            </el-table-column>
            <el-table-column label="商品编号">
              <template slot-scope="scope">
                {{ scope.row.product_sn }}
              </template>
            </el-table-column>
            <el-table-column label="商品名称">
              <template slot-scope="scope">
                {{ scope.row.product_name }}
              </template>
            </el-table-column>
            <el-table-column label="规格型号">
              <template slot-scope="scope">
                {{ scope.row.product_specification }}
              </template>
            </el-table-column>
            <el-table-column label="单位">
              <template slot-scope="scope">
                {{ scope.row.product_unit }}
              </template>
            </el-table-column>
            <el-table-column label="单价">
              <template slot-scope="scope">
                ¥{{ scope.row.entry_price }}
              </template>
            </el-table-column>
            <el-table-column label="数量">
              <template slot-scope="scope">
                <el-input v-model="scope.row.num" type="number" :min="0" :maxlength="20"
                  :disabled="type === 'detail' || type === 'audit'"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="金额">
              <template slot-scope="scope">
                {{ scope.row.num * scope.row.entry_price || 0 }}
              </template>
            </el-table-column>
            <el-table-column label="操作" v-if="type !== 'detail' && type !== 'audit'">
              <template slot-scope="scope">
                <el-button size="mini" type="danger"
                  @click="goodsExchangeAddForm.change_list.splice(scope.$index, 1)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </div>
    </el-form>
    <div class="footer">
      <el-button v-if="type === 'audit'" type="primary" @click="handlePassGoodsExchange()">审核通过
      </el-button>
      <el-button v-if="type === 'audit'" type="danger" @click="dialogVisible = true">审核驳回
      </el-button>
      <el-button v-if="type !== 'audit' && type !== 'detail'" type="primary" @click="submitgoodsExchangeAddForm">保存
      </el-button>
      <el-button @click="$router.back()">返回
      </el-button>
    </div>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <el-form ref="goodsExchangeAddForm" :model="goodsExchangeAddForm" label-width="120px" inline style="width:900px">
        <el-form-item label="驳回原因" prop="reject_reason">
          <el-input v-model="goodsExchangeAddForm.reject_reason" type="textarea" :minlength="0"
            :maxlength="100"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRejectGoodsExchange()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Foundation, RegExp } from '~/ui-utils'
import * as API_GoodsExchange from '@/api/goodsExchange'
import * as API_Setting from '@/api/setting'
import * as API_BasicSetting from '@/api/basicSetting'
import * as API_Erp from '@/api/erp'
import * as API_Auth from '@/api/auth'
export default {
  name: 'goodsExchangeAdd',
  data() {
    const checkPrice = (rule, value, callback) => {
      if (!value && value !== 0) {
        return callback(new Error('换货金额不能为空'))
      } else if (!RegExp.money.test(value)) {
        callback(new Error('请输入正整数或者两位小数'))
      } else if (parseFloat(value) > 99999999) {
        callback(new Error('换货金额设置超过上限值'))
      } else {
        callback()
      }
    }
    return {
      adminList: [],
      dialogVisible: false,
      warehouseList: [],
      deptList: [],
      deptListAll: [],
      id: '',
      type: '',
      /** 出库单表单*/
      goodsExchangeAddForm: {
        change_amount: 0,
        change_list: [],
        return_list: []
      },
      /** 校验规则 */
      goodsExchangeAddFormRule: {
        // change_amount: [
        //   { required: true, message: '请输入换货金额', trigger: 'blur' },
        //   { validator: checkPrice, trigger: 'blur' }
        // ]
      },
      warehouseProduct: null
    }
  },
  mounted() {
    this.GET_DeptList()
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        if (this.$route.name === 'goodsExchangeEdit') {
          this.type = 'edit'
        } else if (this.$route.name === 'goodsExchangeAudit') {
          this.type = 'audit'
        } else if (this.$route.name === 'goodsExchangeReturn') {
          this.type = 'return'
        } else if (this.$route.name === 'goodsExchangeAdd') {
          this.type = 'add'
          this.goodsExchangeAddForm = {
            change_amount: 0,
            change_list: [],
            return_list: [],
            handled_by_id: this.user.uid,
            dept_id: this.user.dept_id
          }
          // this.goodsExchangeAddForm.handled_by_id = this.user.uid
          // this.goodsExchangeAddForm.dept_id = this.user.dept_id
          this.GET_WarehouseList({ dept_id: this.user.dept_id })
          this.$set(this.goodsExchangeAddForm, 'change_time', new Date().getTime())
        } else if (this.$route.name === 'goodsExchangeDetail') {
          this.type = 'detail'
        }
        if (this.$route.params.id) {
          this.id = this.$route.params.id
          this.GET_goodsExchangeAddDetail()
        }
        this.GET_AdministratorList()
      }
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  methods: {
    /** 获取人员列表 */
    GET_AdministratorList() {
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0
      }).then(response => {
        this.adminList = response.data
      })
    },
    /** 清除已选商品明细 */
    cleanGoodsList() {
      // 切换部门或仓库需要清除已选对应仓库下的商品数据
      this.goodsExchangeAddForm.change_list = []
    },
    changewarehouseList(e) {
      this.$set(this.goodsExchangeAddForm, 'warehouse_id', '')
      this.GET_WarehouseList({ dept_id: e })
      this.cleanGoodsList()
    },
    /** 审核-通过 */
    handlePassGoodsExchange() {
      if (this.goodsExchangeAddForm.check_amount_same === false) {
        this.$confirm(this.goodsExchangeAddForm.diff_amount_message, '提示', { type: 'warning' }).then(() => {
          this.$confirm('确定通过吗？', '提示', { type: 'warning' }).then(() => {
            API_GoodsExchange.auditGoodsExchange(this.id, { status: 'PASS' }).then(() => {
              this.$message.success('已通过！')
              const { callback } = this.$route.params
              if (typeof callback === 'function') callback()
              this.$store.dispatch('delCurrentViews', {
                view: this.$route,
                $router: this.$router
              })
              this.$router.push({ name: 'goodsExchange' })
            })
          }).catch(() => { })
        }).catch(() => { })
      } else {
        this.$confirm('确定通过吗？', '提示', { type: 'warning' }).then(() => {
          API_GoodsExchange.auditGoodsExchange(this.id, { status: 'PASS' }).then(() => {
            this.$message.success('已通过！')
            const { callback } = this.$route.params
            if (typeof callback === 'function') callback()
            this.$store.dispatch('delCurrentViews', {
              view: this.$route,
              $router: this.$router
            })
            this.$router.push({ name: 'goodsExchange' })
          })
        }).catch(() => { })
      }
    },
    /** 审核-拒绝 */
    handleRejectGoodsExchange() {
      this.$confirm('确定拒绝吗？', '提示', { type: 'warning' }).then(() => {
        API_GoodsExchange.auditGoodsExchange(this.id, { status: 'REJECT', reject_reason: this.goodsExchangeAddForm.reject_reason }).then(() => {
          this.$message.success('已拒绝！')
          this.dialogVisible = false
          const { callback } = this.$route.params
          if (typeof callback === 'function') callback()
          this.$store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router
          })
          this.$router.push({ name: 'goodsExchange' })
        })
      }).catch(() => { })
    },
    /** 获取仓库 */
    GET_WarehouseList(e) {
      API_BasicSetting.getWarehouseListAll(e).then(response => {
        this.warehouseList = response
      })
    },
    submitgoodsExchangeAddForm() {
      const { id } = this.goodsExchangeAddForm
      const params = this.MixinClone(this.goodsExchangeAddForm)
      if (params.dept_id) { params.dept_name = this.deptListAll.find(dept => dept.id === params.dept_id).name }
      params.staff_name = this.goodsExchangeAddForm.distribution_name
      if (params.warehouse_id) { params.warehouse_name = this.warehouseList.find(ware => ware.id === params.warehouse_id).name }
      if (params.handled_by_id) {
        params.handled_by = this.adminList.find(admin => admin.id === params.handled_by_id).real_name
      }
      params.change_time = Math.floor(params.change_time / 1000)
      if (!params.change_list.length) {
        this.$message.error('请选择换货商品！')
        return
      }
      if (id) {
        API_GoodsExchange.editgoodsExchangeAdd(id, params).then(response => {
          this.$message.success('修改成功！')
          const { callback } = this.$route.params
          if (typeof callback === 'function') callback()
          this.$store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router
          })
          this.$router.push({ name: 'goodsExchange' })
        })
      } else {
        API_GoodsExchange.addgoodsExchangeAdd(params).then(() => {
          this.$message.success('添加成功！')
          const { callback } = this.$route.params
          if (typeof callback === 'function') callback()
          this.$store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router
          })
          this.$router.push({ name: 'goodsExchange' })
        })
      }
    },
    returngoodsExchangeAddForm() {
      const { id } = this.goodsExchangeAddForm
      const params = this.MixinClone(this.goodsExchangeAddForm)
      params.dept_name = this.deptListAll.find(dept => dept.id === params.dept_id).name
      params.staff_name = this.goodsExchangeAddForm.distribution_name
      params.warehouse_name = this.warehouseList.find(ware => ware.id === params.warehouse_id).name
      params.change_time = Math.floor(params.change_time / 1000)
      params.change_list = params.change_list.map(item => {
        item.product_sn = item.product_sn
        item.product_name = item.product_name
        item.specification = item.product_specification
        item.product_id = item.product_id
        item.unit = item.product_unit
        item.stock_sn = item.sn
        item.stock_num = item.remain_num
        item.cost_price = item.product_cost_price
        return item
      })
      API_GoodsExchange.returnGoodsExchange(id, params).then(() => {
        this.$message.success('换货成功！')
        const { callback } = this.$route.params
        if (typeof callback === 'function') callback()
        this.$store.dispatch('delCurrentViews', {
          view: this.$route,
          $router: this.$router
        })
        this.$router.push({ name: 'goodsExchange' })
      })
    },
    // 选择出库单
    async handleSelectWarehouseEntryBatch() {
      if (!this.goodsExchangeAddForm.warehouse_id) {
        this.$message.error('请先选择仓库！')
        return
      }
      const goodsData = await this.$EnwarehouseEntryBatch({
        goodsApi: 'admin/erp/warehouseEntryBatch',
        warehouseList: this.warehouseList,
        selectedIds: this.id ? this.goodsExchangeAddForm.change_list && this.goodsExchangeAddForm.change_list.map(item => item.id) : this.goodsExchangeAddForm.change_list.map(item => item.id),
        purchasePlanApiParams: { warehouse_id: this.goodsExchangeAddForm.warehouse_id }
      })
      this.goodsExchangeAddForm.warehouse_id = goodsData.warehouse_id
      this.goodsExchangeAddForm.change_list = goodsData.purchasePlans.map(item => {
        item.amount = item.entry_price
        item.product_sn = item.product_sn
        item.product_name = item.product_name
        item.specification = item.product_specification
        item.product_id = item.product_id
        item.unit = item.product_unit
        item.stock_sn = item.warehouse_entry_sn
        item.stock_id = item.warehouse_entry_id
        item.stock_batch_sn = item.sn
        item.stock_batch_id = item.id
        item.cost_price = item.product_cost_price
        return item
      })
      this.goodsExchangeAddForm.change_amount = this.goodsExchangeAddForm.change_list.reduce((sum, obj) => sum + obj.entry_price, 0)
    },
    /** 选择订单编号 */
    async handleSelectOrderSn() {
      const orders = await this.$EnPickerOrder({
        orderApi: 'admin/erp/order',
        selectedIds: [this.goodsExchangeAddForm.order_sn],
        limit: 1
      })
      this.$set(this.goodsExchangeAddForm, 'distribution_name', orders[0].distribution_name)
      const orderIds = orders.map(v => v.sn)
      this.$set(this.goodsExchangeAddForm, 'order_sn', orderIds.join(','))
      this.GET_WarehouseOutProduct()
    },
    /** 获取出库单商品明细 */
    async GET_WarehouseOutProduct() {
      const res = await API_Erp.getWarehouseOutProduct({ order_sn: this.goodsExchangeAddForm.order_sn })
      this.goodsExchangeAddForm.return_list = res.data.map(item => {
        item.amount = item.product_price
        item.product_sn = item.product_sn
        item.product_name = item.product_name
        item.specification = item.product_specification
        item.product_id = item.product_id
        item.unit = item.product_unit
        item.num = item.return_num
        item.stock_sn = item.warehouse_entry_sn
        item.cost_price = item.product_cost_price
        return item
      })
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
        this.deptListAll = response
      })
    },
    /** 切换仓库 */
    handleChangeWareHouse(val) {
      this.goodsExchangeAddForm.change_list = []
    },
    /** 获取详情页面数据 */
    GET_goodsExchangeAddDetail() {
      this.$nextTick(() => {
        API_GoodsExchange.getGoodsExchangeInfo(this.id).then(response => {
          this.goodsExchangeAddForm = response
          this.GET_WarehouseList({ dept_id: response.dept_id })
          this.goodsExchangeAddForm.change_time = Math.floor(this.goodsExchangeAddForm.change_time * 1000)
          this.goodsExchangeAddForm.distribution_name = response.staff_name
          this.goodsExchangeAddForm.change_list = response.change_list.map(item => {
            item.entry_price = item.amount
            item.product_specification = item.specification
            item.product_unit = item.unit
            item.warehouse_entry_sn = item.stock_sn
            return item
          })
          this.goodsExchangeAddForm.return_list = response.return_list.map(item => {
            item.product_price = item.amount
            item.product_specification = item.specification
            item.product_unit = item.unit
            item.return_num = item.num
            item.warehouse_entry_sn = item.stock_sn
            return item
          })
          // this.GET_WarehouseOutProduct()
        })
      })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
/deep/ {
}
/** 底部步骤 */
.footer {
  width: 100%;
  padding: 10px;
  bottom: 0px;
  text-align: center;
  z-index: 999;
}

.mx {
  display: flex;
  align-items: center;
  width: 100%;

  .button {
    margin-left: 10px;
  }
}

.change-form {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
  min-width: 900px;

  .change-form-item {
    width: 30%;
    margin: 0 10px 20px 0;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
  }

  /deep/ {
    .el-form-item__content {
      flex: 1;
      width: 100%;
    }

    .el-date-editor,
    .el-cascader,
    .el-select {
      width: 100%;
    }
  }
}

.bg-in-stock {
  background-color: #fff;
  margin: 10px;
  padding: 25px;
}

.goods-info {
  display: flex;

  .goods-name-box {
    text-align: left;

    .goods-name {
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      line-height: 16px;
    }

    .specs {
      color: #999999;
    }
  }
}

/deep/ {
  .el-input--suffix .el-input__inner {
    padding-right: 10px;
  }

  .error-input {
    .el-input__inner {
      border: 1px solid red;
    }
  }
}
</style>
